package org.light.generator;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.utils.StringUtil;
import org.light.verb.ListActive;


public class NamedJavascriptBlockGenerator {
	public static JavascriptBlock documentReadyListDomainList(Domain domain, Var pagesize,Var pagenum){
		JavascriptBlock block = new JavascriptBlock();
		block.setSerial(100);
		block.setStandardName("documentReadyList"+domain.getCapFirstDomainName()+"List");
		StatementList sl = new StatementList();
		sl.add(new Statement(1000,0, "$(document).ready(function(){"));
		sl.add(new Statement(2000,1, "listAll"+StringUtil.capFirst(domain.getPlural())+"ByPage("+pagesize.getVarName()+","+pagenum.getVarName()+");"));
		
		Set<Domain> targetDomains = new TreeSet<Domain>();
		List<Dropdown> myDropdowns = new ArrayList<Dropdown>();
		for (Field f:domain.getFields()) {
			if (f instanceof Dropdown) myDropdowns.add((Dropdown)f);
		}
		for (Dropdown dp:myDropdowns) {
			targetDomains.add(dp.getTarget());
		}
		
		long serial = 3000L;
		for (Domain d:targetDomains) {
			sl.add((new Statement(serial,1, NamedJavascriptMethodGenerator.generateFectchDomainData(d,new ListActive(d), new Var(d.getLowerFirstDomainName()+"Data",new Type("var"))).generateStandardMethodCallString()+";")));
			sl.add((new Statement(serial+1000L,1,"$(\"#add"+domain.getCapFirstDomainName()+"Row\").find(\"#"+d.getLowerFirstDomainName()+"Id\").html("+NamedJavascriptMethodGenerator.generateGenerateDomainOptionsWithoutValue(d,new Var(d.getLowerFirstDomainName()+"Id",new Type("var")),new Var(d.getLowerFirstDomainName()+"Data",new Type("var"))).generateStandardMethodCallString()+");")));
			serial += 2000L;
		}
		
		sl.add(new Statement(serial,0, "});"));
		block.setMethodStatementList(sl);
		return block;
	}
	
	public static JavascriptBlock generateDocumentReadyCallListMyActiveMastersBlock(Domain master){
		JavascriptBlock block = new JavascriptBlock();
		block.setSerial(200);
		block.setStandardName("documentReadyCallListActiveMastersBlock");

		StatementList sl = new StatementList();
		sl.add(new Statement(1000L,0, "$(document).ready(function() {"));
		sl.add(new Statement(2000L,1, "loadMy"+master.getCapFirstPlural()+"();"));
		sl.add(new Statement(3000L,0, "});"));
		block.setMethodStatementList(sl);
		return block;
	}
}
